package view;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;

import dao.OrdersDao;
import modle.Country;
import modle.Orders;
import util.DbUtil;
import util.StringUtil;
import view.Ship_Orders.MyTableModel;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import java.awt.Toolkit;

public class Customer_Menu extends JFrame {

	private JPanel contentPane;
	private JButton btnOrder;
	private JButton btnFind;
	private JButton btnBack;
	private JTable table;
	private JLabel OrderId;
	private JLabel Customer_Menu;
	private JTextField textField;
	private int Id;
	private JComboBox comboBox;
	private List<Country> listCountries;
	private Locale locale;
	ResourceBundle rd;
	private Object[][] rowData = new Object[100][3];
	
	/**
     * 表头（列名）
     */
    private Object[] columnNames = {"订单的编号", "菜品是否已发货", "用户的编号"};

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Customer_Menu frame = new Customer_Menu(1);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Customer_Menu(int id) {
		setIconImage(Toolkit.getDefaultToolkit().getImage(Customer_Menu.class.getResource("/img/iconImage.jpg")));
		setTitle("Welcome to Food Corner");
		
		Id = id;
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 549, 473);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		Customer_Menu = new JLabel("Customer Menu");
		Customer_Menu.setForeground(new Color(165, 42, 42));
		Customer_Menu.setFont(new Font("微软雅黑", Font.BOLD, 19));
		Customer_Menu.setBounds(180, 13, 170, 32);
		contentPane.add(Customer_Menu);
		
		btnOrder = new JButton("Order");
		btnOrder.setFont(new Font("微软雅黑", Font.BOLD, 17));
		btnOrder.setBounds(399, 341, 103, 32);
		contentPane.add(btnOrder);
		btnOrder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Order(id).setVisible(true);
				dispose();
			}
		});
		
		btnFind = new JButton("Find");
		btnFind.setFont(new Font("微软雅黑", Font.BOLD, 17));
		btnFind.setBounds(399, 238, 103, 32);
		contentPane.add(btnFind);
		btnFind.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Find();
			}
		});
		
		btnBack = new JButton("Back");
		btnBack.setFont(new Font("微软雅黑", Font.PLAIN, 17));
		btnBack.setBounds(14, 371, 74, 32);
		contentPane.add(btnBack);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(14, 69, 503, 139);
		contentPane.add(scrollPane);
		
		table = new JTable(new MyTableModel());
		table.setRowHeight(25);										//设置table行高
		table.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
		scrollPane.setViewportView(table);
		
		textField = new JTextField();
		textField.setBounds(223, 238, 162, 32);
		contentPane.add(textField);
		textField.setColumns(10);
		
		OrderId = new JLabel("Order's id：");
		OrderId.setFont(new Font("微软雅黑", Font.PLAIN, 19));
		OrderId.setBounds(79, 237, 130, 32);
		contentPane.add(OrderId);
		
		JLabel lblNewLabel_3 = new JLabel("");
		lblNewLabel_3.setIcon(new ImageIcon(Customer_Menu.class.getResource("/img/find2.png")));
		lblNewLabel_3.setBounds(24, 233, 42, 37);
		contentPane.add(lblNewLabel_3);
		
		JLabel lblNewLabel_1 = new JLabel("");
		lblNewLabel_1.setIcon(new ImageIcon(Customer_Menu.class.getResource("/img/customerorder2.jpg")));
		lblNewLabel_1.setBounds(344, 332, 42, 41);
		contentPane.add(lblNewLabel_1);
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Customer_Login().setVisible(true);
				dispose();
			}
		});
		
		comboBox = new JComboBox<>();						//组合按钮或可编辑字段和下拉列表的组件
		comboBox.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		comboBox.addItemListener(new ItemListener() {		//用于接收项目事件的侦听器接口。
			public void itemStateChanged(ItemEvent e) {
				int index = comboBox.getSelectedIndex();	//返回列表中与给定项目匹配的第一个项目。 
					String arr[] = listCountries.get(index).getId().split("-");					//  ???（应该是遇见 - 就分割）
					locale = new Locale(arr[0], arr[1]);//	???   Locale对象代表具体的地理，政治或文化地区。（第一个是语言，第二个是国家）
					rd = ResourceBundle.getBundle("resources.content", locale);		//使用指定的基本名称，区域设置和类加载器获取资源包（这里好像没用类加载器）。 
					try {
						changeLanguage();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
			}
		});
		comboBox.setBounds(419, 14, 98, 32);
		contentPane.add(comboBox);
		
		fillCountries();
	}
	
	protected void Find() {
		// TODO Auto-generated method stub
		if(!StringUtil.isNum(textField.getText()))
		{
			JOptionPane.showMessageDialog(null, "请输入正确的订单号！");
			return;
		}
		
		if (StringUtil.isEmpty(textField.getText())) {
			JOptionPane.showMessageDialog(null, "ID不能为空！");
			return;
		}
		
		int id = Integer.valueOf(textField.getText());
		
		DbUtil dbUtil = new DbUtil();
		Connection con = null;
		
		try {

			con = dbUtil.getCon();
			Orders orders = OrdersDao.OrdersSearch(con, id);
			
			if(orders==null)
			{
				JOptionPane.showMessageDialog(null, "请输入正确的订单号！");
				return;
			}
			
			if(orders.getCustomer()!=Id)
			{
				JOptionPane.showMessageDialog(null, "这不是您的订单，您无权查询！");
				return;
			}
			
			new Receipt(Id, id).setVisible(true);
			dispose();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public class MyTableModel extends AbstractTableModel {
        /**
         * 表格所有行数据
         */
			
		private int num = 0;
        
        public MyTableModel() {
//        	Orders orders = null;
        	ResultSet rs;
        	
    		try {
    			rs = OrdersDao.OrdersSearch_set(DbUtil.getCon(), Id);
				while(rs.next())
				{
					rowData[num][0] = rs.getInt("Id");
					if(rs.getInt("Status")==0)   rowData[num][1] = "未发货";
					else   rowData[num][1] = "已发货";
					rowData[num][2] = rs.getInt("Customer");
					num++;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//        	return rowData;
        }

		/**
         * 返回总行数
         */
        @Override
        public int getRowCount() {
            return num;
        }

        /**
         * 返回总列数
         */
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        /**
         * 返回列名称（表头名称），AbstractTableModel 中对该方法的实现默认是以
         * 大写字母 A 开始作为列名显示，所以这里需要重写该方法返回我们需要的列名。
         */
        @Override
        public String getColumnName(int column) {
            return columnNames[column].toString();
        }

        /**
         * 返回指定单元格的显示的值
         */
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return rowData[rowIndex][columnIndex];
        }
    }
	
	private void fillCountries() {
		// TODO Auto-generated method stub
		listCountries = new ArrayList<Country>();
		listCountries.add(new Country("en-US", "English"));
		listCountries.add(new Country("zh-CN", "中文"));
		
		for(Country c : listCountries)
			comboBox.addItem(c.getName());
	}

	protected void changeLanguage() {
		// TODO Auto-generated method stub
		
		Customer_Menu.setText(rd.getString("Customer_Menu"));
		OrderId.setText(rd.getString("OrderId"));
		btnFind.setText(rd.getString("btnFind"));
		btnOrder.setText(rd.getString("btnOrder"));
		btnBack.setText(rd.getString("btnBack"));
	}
}
